import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Heart, X, MapPin, Calendar, Star, Sparkles } from 'lucide-react';
import { useSwipeable } from 'react-swipeable';
import { useAuthStore, useMatchStore } from '../stores';
import { apiService } from '../services/api';
import toast from 'react-hot-toast';
import type { RecommendationUser } from '../types/api';

const HomePage: React.FC = () => {
  const { user } = useAuthStore();
  const { addMatch } = useMatchStore();
  const [users, setUsers] = useState<RecommendationUser[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [isSwiping, setIsSwiping] = useState(false);

  // 获取推荐用户
  useEffect(() => {
    const fetchRecommendations = async () => {
      if (!user) return;

      try {
        const response = await apiService.getRecommendations(user.user_id, 1, 20);
        if (response.code === 0) {
          setUsers(response.data?.users || []);
        }
      } catch (error) {
        console.error('Fetch recommendations error:', error);
        toast.error('获取推荐用户失败');
      } finally {
        setIsLoading(false);
      }
    };

    fetchRecommendations();
  }, [user]);

  // 滑动操作处理
  const handleSwipe = async (action: 'like' | 'pass') => {
    if (!user || currentIndex >= users.length || isSwiping) return;

    const currentUser = users[currentIndex];
    setIsSwiping(true);

    try {
      const response = await apiService.swipeUser({
        user_id: user.user_id,
        target_user_id: currentUser.user_id,
        action: action === 'like' ? 1 : 2,
      });

      if (response.code === 0) {
        if (response.data.is_match && action === 'like') {
          toast.success('恭喜！你们匹配成功了！');
          // 添加到匹配列表
          addMatch({
            match_id: Date.now(), // 临时ID
            user_id: currentUser.user_id,
            nickname: currentUser.nickname,
            avatar: currentUser.avatar,
            bio: currentUser.bio,
            match_time: new Date().toISOString(),
            interests: currentUser.interests || [],
          });
        } else if (action === 'like') {
          toast.success('已发送喜欢！');
        }
      }
    } catch (error) {
      console.error('Swipe error:', error);
    } finally {
      setIsSwiping(false);
      setCurrentIndex(prev => prev + 1);
    }
  };

  // 手势处理
  const swipeHandlers = useSwipeable({
    onSwipedLeft: () => handleSwipe('pass'),
    onSwipedRight: () => handleSwipe('like'),
    preventDefaultTouchmoveEvent: true,
    trackMouse: true,
  });

  const currentUser = users[currentIndex];

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">正在为你寻找合适的人...</p>
        </div>
      </div>
    );
  }

  if (!currentUser) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-20 h-20 bg-gray-200 rounded-full mx-auto mb-4 flex items-center justify-center">
            <Heart className="text-gray-400" size={32} />
          </div>
          <h2 className="text-xl font-semibold text-gray-900 mb-2">暂时没有更多推荐</h2>
          <p className="text-gray-600">稍后再来看看，或者调整你的筛选条件</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 pt-20">
      <div className="max-w-md mx-auto px-4">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-6"
        >
          <h1 className="text-2xl font-bold text-gray-900">发现</h1>
          <p className="text-gray-600">滑动卡片来认识新朋友</p>
        </motion.div>

        {/* 用户卡片 */}
        <div className="relative h-[600px] mb-8">
          <AnimatePresence>
            <motion.div
              key={currentUser.user_id}
              {...swipeHandlers}
              initial={{ opacity: 0, scale: 0.8, rotate: 0 }}
              animate={{ opacity: 1, scale: 1, rotate: 0 }}
              exit={{ opacity: 0, scale: 0.8, rotate: 0 }}
              drag="x"
              dragConstraints={{ left: 0, right: 0 }}
              dragElastic={0.2}
              onDragEnd={(_, info) => {
                if (info.offset.x > 100) {
                  handleSwipe('like');
                } else if (info.offset.x < -100) {
                  handleSwipe('pass');
                }
              }}
              className="absolute inset-0 bg-white rounded-2xl shadow-xl overflow-hidden cursor-grab active:cursor-grabbing"
            >
              {/* 用户头像 */}
              <div className="relative h-2/3">
                <img
                  src={currentUser.avatar || '/api/placeholder/400/600'}
                  alt={currentUser.nickname}
                  className="w-full h-full object-cover"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent" />
                
                {/* 用户信息覆盖层 */}
                <div className="absolute bottom-4 left-4 right-4 text-white">
                  <h2 className="text-2xl font-bold mb-1">{currentUser.nickname}</h2>
                  <div className="flex items-center space-x-4 text-sm">
                    {currentUser.age && (
                      <span className="flex items-center">
                        <Calendar size={16} className="mr-1" />
                        {currentUser.age}岁
                      </span>
                    )}
                    {currentUser.location && (
                      <span className="flex items-center">
                        <MapPin size={16} className="mr-1" />
                        {currentUser.location}
                      </span>
                    )}
                    {currentUser.distance && (
                      <span className="flex items-center">
                        <MapPin size={16} className="mr-1" />
                        {currentUser.distance}km
                      </span>
                    )}
                  </div>
                </div>

                {/* 兼容度分数 */}
                {currentUser.compatibility_score && (
                  <div className="absolute top-4 right-4 bg-white/90 backdrop-blur-sm rounded-full px-3 py-1 flex items-center">
                    <Star className="text-yellow-500 mr-1" size={16} />
                    <span className="text-sm font-semibold">
                      {Math.round(currentUser.compatibility_score * 100)}%
                    </span>
                  </div>
                )}
              </div>

              {/* 用户详情 */}
              <div className="p-6 h-1/3 overflow-y-auto">
                {currentUser.bio && (
                  <p className="text-gray-700 mb-4">{currentUser.bio}</p>
                )}
                
                {/* 兴趣标签 */}
                {currentUser.interests && currentUser.interests.length > 0 && (
                  <div>
                    <h3 className="text-sm font-semibold text-gray-900 mb-2">兴趣爱好</h3>
                    <div className="flex flex-wrap gap-2">
                      {currentUser.interests.slice(0, 6).map((interest) => (
                        <span
                          key={interest.tag_id}
                          className="px-2 py-1 bg-primary-100 text-primary-700 rounded-full text-xs"
                        >
                          {interest.tag_name}
                        </span>
                      ))}
                      {currentUser.interests.length > 6 && (
                        <span className="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs">
                          +{currentUser.interests.length - 6}
                        </span>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </motion.div>
          </AnimatePresence>
        </div>

        {/* 操作按钮 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="flex justify-center space-x-8 mb-8"
        >
          {/* 无感按钮 */}
          <motion.button
            whileHover={{ scale: 1.1 }}
            whileTap={{ scale: 0.9 }}
            onClick={() => handleSwipe('pass')}
            disabled={isSwiping}
            className="w-14 h-14 bg-gray-200 hover:bg-gray-300 rounded-full flex items-center justify-center transition-colors duration-200 disabled:opacity-50"
          >
            <X className="text-gray-600" size={24} />
          </motion.button>

          {/* 喜欢按钮 */}
          <motion.button
            whileHover={{ scale: 1.1 }}
            whileTap={{ scale: 0.9 }}
            onClick={() => handleSwipe('like')}
            disabled={isSwiping}
            className="w-16 h-16 bg-primary-500 hover:bg-primary-600 rounded-full flex items-center justify-center transition-colors duration-200 disabled:opacity-50"
          >
            <Heart className="text-white" size={28} />
          </motion.button>

          {/* 超级喜欢按钮 */}
          <motion.button
            whileHover={{ scale: 1.1 }}
            whileTap={{ scale: 0.9 }}
            onClick={() => handleSwipe('like')}
            disabled={isSwiping}
            className="w-14 h-14 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 rounded-full flex items-center justify-center transition-colors duration-200 disabled:opacity-50"
          >
            <Sparkles className="text-white" size={24} />
          </motion.button>
        </motion.div>

        {/* 进度指示器 */}
        <div className="flex justify-center space-x-2 mb-8">
          {users.slice(0, 5).map((_, index) => (
            <div
              key={index}
              className={`w-2 h-2 rounded-full transition-colors duration-200 ${
                index === currentIndex ? 'bg-primary-500' : 'bg-gray-300'
              }`}
            />
          ))}
          {users.length > 5 && (
            <span className="text-xs text-gray-500 ml-2">
              {currentIndex + 1}/{users.length}
            </span>
          )}
        </div>
      </div>
    </div>
  );
};

export default HomePage;
